package com.xiaodu.acer.phoneplay.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.LayoutInflaterCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.context.IconicsLayoutInflater;
import com.mikepenz.ionicons_typeface_library.Ionicons;
import com.orhanobut.logger.Logger;
import com.xiaodu.acer.phoneplay.App;
import com.xiaodu.acer.phoneplay.R;
import com.xiaodu.acer.phoneplay.bean.FragmentInfo;
import com.xiaodu.acer.phoneplay.bean.User;
import com.xiaodu.acer.phoneplay.common.Constant;
import com.xiaodu.acer.phoneplay.common.font.CustomFont;
import com.xiaodu.acer.phoneplay.common.rx.RxBus;
import com.xiaodu.acer.phoneplay.di.component.AppComponent;
import com.xiaodu.acer.phoneplay.di.component.DaggerMainComponent;
import com.xiaodu.acer.phoneplay.di.module.MainModule;
import com.xiaodu.acer.phoneplay.presenter.MainPresenter;
import com.xiaodu.acer.phoneplay.presenter.contract.MainContract;
import com.xiaodu.acer.phoneplay.ui.adapter.ViewPagerAdapter;
import com.xiaodu.acer.phoneplay.ui.fragment.CategoryFragment;
import com.xiaodu.acer.phoneplay.ui.fragment.GamesFragment;
import com.xiaodu.acer.phoneplay.ui.fragment.RankingFragment;
import com.xiaodu.acer.phoneplay.ui.fragment.RecommendFragment;
import com.xiaodu.acer.phoneplay.ui.fragment.WelcomeFragment;
import com.xiaodu.acer.phoneplay.widget.BadgeActionProvider;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.functions.Consumer;
import library.imageloader.GlideCircleTransform;
import library.util.ACache;

public class MainActivity extends AppCompatActivity
        implements MainContract.View {

    private static final String TAG = MainActivity.class.getName();
    @BindView(R.id.navigation_view)
    NavigationView mNavigationView;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.tool_bar)
    Toolbar mToolBar;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    private ActionBarDrawerToggle drawerToggle;

    /**
     * 用户头部控件
     */
    private View mHeaderView;
    private TextView mHeaderTextView;
    private ImageView mHeaderImageView;


    @Inject
    MainPresenter mPresenter;

    //初始化Handler
    private Handler mHandler = new Handler();
    private WelcomeFragment mWelcomeFragment;
    private ViewStub mViewStub;

    private Unbinder mUnbinder;
    private App mApplication;
    private BadgeActionProvider mBadgeActionProvider;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate()));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mApplication = (App) getApplication();
        setupAcitivtyComponent(mApplication.getAppComponent());
        initWelcome();

        onclick();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != Unbinder.EMPTY) {
            mUnbinder.unbind();
        }
    }

    public void setupAcitivtyComponent(AppComponent appComponent) {
        DaggerMainComponent.builder()
                .appComponent(appComponent)
                .mainModule(new MainModule(this))
                .build()
                .inject(MainActivity.this);
    }


    /**
     * 初始化启动页
     */
    private void initWelcome() {
        mViewStub = findViewById(R.id.viewstub);
        mWelcomeFragment = new WelcomeFragment();
//        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.replace(R.id.frame, mWelcomeFragment);
//        transaction.commit();

//        //1.判断当窗体加载完毕的时候,立马再加载真正的布局进来
//        getWindow().getDecorView().post(new Runnable() {
//            @Override
//            public void run() {
//                // 开启延迟加载
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        //将viewstub加载进来
//
//
//                        Log.e(TAG, "run:  getWindow().getDecorView() ");
//                    }
//                });
//            }
//        });
        // TODO: 2018/1/10 待优化
        mViewStub.inflate();
        mUnbinder = ButterKnife.bind(MainActivity.this);
        initDrawerLayout();
        initTablayout();
        initUser();

        mPresenter.requestPermisson();
        mPresenter.getAppUpdateInfo();

//        //2.判断当窗体加载完毕的时候执行,延迟一段时间做动画。
//        getWindow().getDecorView().post(new Runnable() {
//
//            @Override
//            public void run() {
//                // 开启延迟加载,也可以不用延迟可以立马执行（我这里延迟是为了实现fragment里面的动画效果的耗时）
//                mHandler.postDelayed(new DelayRunnable(MainActivity.this, mWelcomeFragment), 0);
////                mPresenter.requestPermisson();
////                mPresenter.getAppUpdateInfo();
//            }
//        });

    }

    /**
     * 初始化ViewPager的Fragment
     *
     * @return
     */
    private List<FragmentInfo> initFragments() {

        List<FragmentInfo> mFragments = new ArrayList<>(4);
        mFragments.add(new FragmentInfo("推荐", RecommendFragment.class));
        mFragments.add(new FragmentInfo("排行", RankingFragment.class));

        mFragments.add(new FragmentInfo("游戏", GamesFragment.class));
        mFragments.add(new FragmentInfo("分类", CategoryFragment.class));

        return mFragments;
    }


    private void initTablayout() {
        PagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), initFragments());
        mViewPager.setOffscreenPageLimit(adapter.getCount());
        mViewPager.setAdapter(adapter);

        mTabLayout.setupWithViewPager(mViewPager);

        MenuItem downloadMenuItem = mToolBar.getMenu().findItem(R.id.action_download);

        mBadgeActionProvider = (BadgeActionProvider) MenuItemCompat.getActionProvider(downloadMenuItem);

        mBadgeActionProvider.setIcon(DrawableCompat.wrap(new IconicsDrawable(this,
                CustomFont.Icon.cniao_download).color(ContextCompat.getColor(this, R.color.white))));
        mBadgeActionProvider.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toAppManagerActivity(mBadgeActionProvider.getBadgeNum() > 0 ? 2 : 0);
            }
        });


    }

    /**
     * 跳转至AppManagerActivity页面
     *
     * @param position
     */
    private void toAppManagerActivity(int position) {
        Intent intent = new Intent(MainActivity.this, AppManagerActivity.class);
        intent.putExtra(Constant.POSITION, position);
        startActivity(new Intent(intent));
    }


    /**
     * 初始化左边的框
     */
    private void initDrawerLayout() {

        mHeaderView = mNavigationView.getHeaderView(0);
        mHeaderImageView = mHeaderView.findViewById(R.id.img_avatar);


        mNavigationView.getMenu().findItem(R.id.menu_app_update).setIcon(new IconicsDrawable(this, Ionicons.Icon.ion_ios_loop));
        mNavigationView.getMenu().findItem(R.id.menu_download_manager).setIcon(new IconicsDrawable(this, CustomFont.Icon.cniao_download));
        mNavigationView.getMenu().findItem(R.id.menu_app_uninstall).setIcon(new IconicsDrawable(this, Ionicons.Icon.ion_ios_trash_outline));
        mNavigationView.getMenu().findItem(R.id.menu_setting).setIcon(new IconicsDrawable(this, Ionicons.Icon.ion_ios_gear_outline));

        mNavigationView.getMenu().findItem(R.id.menu_logout).setIcon(new IconicsDrawable(this, CustomFont.Icon.cniao_shutdown));


        //默认图片
        mHeaderImageView.setImageDrawable(new IconicsDrawable(this, CustomFont.Icon.cniao_head)
                .color(ContextCompat.getColor(this, R.color.white)));
        mHeaderTextView = mHeaderView.findViewById(R.id.txt_username);

        //调用menu布局
        mToolBar.inflateMenu(R.menu.toolbar_menu);
        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar, R.string.open, R.string.close);
        drawerToggle.syncState();
        mDrawerLayout.addDrawerListener(drawerToggle);

        RxBus.getDefault()
                .toObservable(User.class)
                .subscribe(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        initUserHeadView(user);
                    }
                });


    }

    /**
     * 初始化头像和昵称
     *
     * @param user
     */
    private void initUserHeadView(User user) {
        // TODO: 2018/1/11 待封装
        Glide.with(this).load("http:" + user.getLogo_url())
                .transform(new GlideCircleTransform(this)).into(mHeaderImageView);

        mHeaderTextView.setText(user.getUsername());

    }

    /**
     * 初始化用户信息
     */
    private void initUser() {
        ACache aCache = ACache.get(this);
        User user = (User) aCache.getAsObject(Constant.USER);
        //如果是空的，按钮的点击事件可以跳转到登录页
        if (user == null) {
            mHeaderImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
            });
        } else {//如果不为空，再次设置用户状态
            initUserHeadView(user);
        }
    }

    @Override
    public void requestPermissonSuccess() {

    }

    @Override
    public void requestPermissonFail() {
        Toast.makeText(mApplication, "获取权限失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void changeAppNeedUpdateCount(int count) {
        Logger.e(count + "");
        if (count > 0) {
            mBadgeActionProvider.setText(count + "");
        } else {
            mBadgeActionProvider.hideBadge();
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void dismissLoading() {

    }

    @Override
    public void showError(String error) {

    }

    public void onclick() {
        if (mHeaderImageView != null) {
            mHeaderImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
            });
        }

        mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.action_search) {
                    startActivity(new Intent(MainActivity.this, SearchActivity.class));
                }
                return true;
            }
        });


        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_download_manager:
                        toAppManagerActivity(Constant.DOWNLOADING_FRAGMENT);
                        break;
                    case R.id.menu_app_uninstall:
                        toAppManagerActivity(Constant.INSTALLEDAPP_APP_FRAGMENT);
                        break;
                    case R.id.menu_app_update:
                        toAppManagerActivity(Constant.UPGRADE_APP_FRAGMENT);
                        break;
                    case R.id.menu_setting:
                        startActivity(new Intent(MainActivity.this, SettingActivity.class));
                        break;
                    case R.id.menu_logout:  //退出登录
                        logout();
                    default:
                        break;
                }
                return false;
            }


        });

    }

    /**
     * 退出登录
     */
    private void logout() {
        //清理用户数据
        ACache aCache = ACache.get(this);
        aCache.put(Constant.USER, "");
        aCache.put(Constant.TOKEN, "");

        // TODO: 2018/1/11 还能再优化按钮的点击事件
        //恢复头部为默认状态，点击按钮进入登录页面
        mHeaderImageView.setImageResource(R.mipmap.ic_launcher);
        mHeaderTextView.setText("未登录");

        mHeaderImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        });

        Toast.makeText(MainActivity.this, "您已退出登录", Toast.LENGTH_LONG).show();
    }

    static class DelayRunnable implements Runnable {
        private WeakReference<Context> contextRef;
        private WeakReference<WelcomeFragment> mWelcomeFragment;

        public DelayRunnable(Context context, WelcomeFragment f) {
            contextRef = new WeakReference<Context>(context);
            mWelcomeFragment = new WeakReference<WelcomeFragment>(f);
        }

        @Override
        public void run() {
            // 移除fragment
            if (contextRef != null) {
                WelcomeFragment splashFragment = mWelcomeFragment.get();
                if (splashFragment == null) {
                    return;
                }
                FragmentActivity activity = (FragmentActivity) contextRef.get();
                FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
                transaction.remove(splashFragment);
                transaction.commitAllowingStateLoss();


            }
        }
    }

}
